package be.groept.ace.enquete.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import be.groept.ace.enquete.model.beans.User;
import be.groept.ace.enquete.model.dao.DAOCommand;
import be.groept.ace.enquete.model.dao.DAOFactory;
import be.groept.ace.enquete.model.dao.DAOManager;
import be.groept.ace.enquete.model.exceptions.DAOException;
import be.groept.ace.enquete.utils.BeanUtils;

/**
 * Servlet implementation class AdminUserServlet
 */
@WebServlet("/admin/user/*")
public class AdminUserServlet extends AdminServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(AdminUserServlet.class);

	@Override
	protected int handleGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String idParam = request.getParameter("id");
		@SuppressWarnings("unchecked")
		List<String> errors = (List<String>) request.getAttribute("errors");
		if(idParam != null) {
			try {
				final int id = Integer.parseInt(idParam);
				DAOManager daoManager = null;
				try {
					daoManager  = (new DAOFactory()).createDAOManager(DAOFactory.PERSISTENCEMODE.MYSQL);
				} catch (DAOException daoe) {
					logger.fatal(daoe.toString());
					throw new ServletException(daoe.getMessage() + "\nPlease configure the resource in the META_INF/context.xml file");
				}
				User user = (User) daoManager.transactionAndClose(new DAOCommand() {
					
					@Override
					public Object execute(DAOManager daoManager) throws DAOException {
						return daoManager.getUserDAO().findUserByPK(id);
					}
				});
				if (user == null) {
					logger.error("No user found with id: " + id);
					errors.add("No user found with id: " + id);
				}
				request.setAttribute("userEdit", user);
			} catch (DAOException daoe) {
				logger.error(daoe.toString());
				errors.add(daoe.getMessage());
			} catch (NumberFormatException nfe) {
				logger.error(nfe.getMessage());
				errors.add("id moet een numerieke waarde hebben");
			}
		} 
		
		setUserFormAttributes(request, response);
		return 200;
	}

	@Override
	protected int handlePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		@SuppressWarnings("unchecked")
		List<String> errors = (List<String>) request.getAttribute("errors");
		User updatedUser = null;
		String idParam = request.getParameter("userid");
		try {
			final int userid = Integer.parseInt(idParam);
			
			DAOManager daoManager = null;
			try {
				daoManager  = (new DAOFactory()).createDAOManager(DAOFactory.PERSISTENCEMODE.MYSQL);
			} catch (DAOException daoe) {
				logger.fatal(daoe.toString());
				throw new ServletException(daoe.getMessage() + "\nPlease configure the resource in the META_INF/context.xml file");
			}
			final User user = new User();
			BeanUtils.mapUserPostParameters(user, request.getParameterMap(), logger);
			updatedUser = user;
			if(user.isValidForForm(errors)) {
				if (userid == -1) {
					
					daoManager.transactionAndClose(new DAOCommand() {
						
						@Override
						public Object execute(DAOManager daoManager) throws DAOException {
							daoManager.getUserDAO().insertUser(user);
							return null;
						}
					});
					
					request.setAttribute("success", "Gebruiker is succesvol bewaard");
				} else {
					user.setId(userid);
					updatedUser = (User) daoManager.transactionAndClose(new DAOCommand() {
						@Override
						public Object execute(DAOManager daoManager) throws DAOException {
							daoManager.getUserDAO().updateUser(user);
							return daoManager.getUserDAO().findUserByEmail(user.getEmail());
						}
					});
					request.setAttribute("success", "Gebruiker is succesvol bewaard");
				}
			}
		}catch (NumberFormatException nfe) {
			logger.error(nfe.getMessage());
			errors.add("id moet een numerieke waarde hebben");
		} catch (DAOException daoe) {
			logger.error(daoe.toString());
			errors.add(daoe.getMessage());
		}
		request.setAttribute("userEdit", updatedUser);
		setUserFormAttributes(request, response);
		return 200;
	}
	
	private void setUserFormAttributes(HttpServletRequest request, HttpServletResponse response) {
		setForm(request, true);
		setFormActionUrl(request, response.encodeURL(request.getContextPath() + "/admin/user"));
		setPage(request, "userForm");
		setTitle(request, "Manage gebruiker");
		setNavigationSelectedLink(request, 2);
		addHeaderLink(request, 1, "Bewaar", "save");
	}

}
